//
//  HistoryVc.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/3/11.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit

class HistoryVc: TTBaseVC {
    var page:Int = 1
    var totalPage:Int = 1
    
    let HistoryTableViewCellID = "HistoryTableViewCell"
    
    var listModelArr:[ListenListModel] = [ListenListModel]()
    
    private lazy var tableView: TTTableView = {
        let tableView = TTTableView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = WhiteBackColor
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(NIBNAME(HistoryTableViewCellID), forCellReuseIdentifier: HistoryTableViewCellID)
        tableView.tableFooterView = UIView.init(frame: .zero)
        tableView.tableHeaderView = UIView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 0))
    
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "历史"

        self.view.addSubview(tableView)
        tableView.backgroundColor = UIColor.clear
        
        setData()
    }
    
}

//  MARK: - ###### 方法 ######
extension HistoryVc {
    func setData() {
        MTProgressHUD.show()
        HomeRequestModel.loadHistoryAndCollectData(programId:[String.getUserId(),0],parameters: ["startPoint":self.page,"maxPage":999]) { (success, message, model, page) in
            if success && model != nil {
                self.listModelArr = model!
            }
            self.tableView.reloadData()
            if self.listModelArr.count == 0 {
                self.tableView.setNoData(nodata: true)
            } else {
                self.tableView.setNoData(nodata: false)
            }
            MTProgressHUD.hidded(true)
        }
    }
    
    func getProgress(id:Int) -> Int {
        var dic = UserDefaults.standard.dictionary(forKey: PlayDictionary)
        if dic!["\(id)"] != nil {
            return Int(dic!["\(id)"] as! Double)
        } else {
            return 0
        }
    }
    
    func getMMSSFromSS(duration:Int)->(String){
        var min = duration / 60
        let sec = duration % 60
        var hour : Int = 0
        if min >= 60 {
            hour = min / 60
            min = min % 60
            if hour > 0 {
                return String(format: "%02d:%02d:%02d", hour, min, sec)
            }
        }
        return String(format: "%02d:%02d", min, sec)
    }
}

//  MARK: - ###### 协议 ######
extension HistoryVc: UITableViewDelegate, UITableViewDataSource, HistoryTableViewCellDelegate {
    func findActionDele(cell: UITableViewCell) {
        let index:IndexPath = self.tableView.indexPath(for: cell) as! IndexPath
        let model = self.listModelArr[index.row]
        
        let find = FindView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
        find.modelList = model
        find.dateBlock = { (num) in
            switch num {
            case 11:
                let vc = FindVc()
                vc.programId = self.listModelArr[index.row].categoryId
                PUSHVIEWCONTROLLER(vc)
            case 12:
                self.setData()
            case 13:
                self.setData()
                
            case 14:
                HomeRequestModel.loadResourcesData(parameters: ["flg":"go_download"]) { (success, message, urlStr) in
                    if success {
                        let newUrl = urlStr + "?srcUserId=\(String.getUserId())"
                        let share = ShareView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), title: model.title ?? "天天必听", des: model.describe ?? "分享免费听", url: newUrl ?? "https://itunes.apple.com/cn/app/天天必听/id1449930721", image: model.shareImageUrl ?? "http://source.blistening.cn/bt_source/ttbt/logo/logo.png")
                        UIApplication.shared.keyWindow?.addSubview(share)
                    }
                }
            default:
                return
            }
            
        }
        UIApplication.shared.keyWindow?.addSubview(find)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listModelArr.count
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 94
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: HistoryTableViewCellID) as! HistoryTableViewCell
        cell.backgroundColor = UIColor.clear
        cell.selectionStyle = .none
        let model = self.listModelArr[indexPath.row]
        cell.delegate = self
        cell.leftImageView.sd_setImage(with: URL(string: StringIncludeChineseToString(model.shareImageUrl ?? "")), completed: nil)
        cell.titleLabel.text = model.title
        cell.desLabel.text = model.describe
        cell.newLabel.text = "\(model.totalSeason)集更新"
        cell.playLabel.text = "播放至\(getMMSSFromSS(duration: getProgress(id: model.id)))"
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.listModelArr[indexPath.row]
        let playVc = PlayVC()
        playVc.id = model.id
        PUSHVIEWCONTROLLER(playVc)
    }
}
